package com.ms.convert.utils;

import com.jacob.com.LibraryLoader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;

/**
 * 工具
 *
 * @author Dizzy
 */
@Slf4j
public class Utils {

    /**
     * 加载DLL文件并设置到系统环境中
     *
     * @param appDir src/main/resources
     * @throws IOException
     */
    public static void loadLibrary(final String appDir) throws IOException {
        final String libFile = "amd64".equals(System.getProperty("os.arch")) ? "jacob-1.14.3-x64.dll" : "jacob-1.14.3-x86.dll";
        // 复制到JacobDll 路径
        String dir = copyFile("lib/" + libFile, "lib/" + libFile);

        // 复制当前jdk bin 目录位置
//        String property = System.getProperty("java.home");
//        String javaPath = property + "\\bin";
//        copyFile("lib\\" + libFile, javaPath + "\\" + libFile);

        String lib = Paths.get(appDir, "lib/" + libFile).toString();
        System.setProperty(LibraryLoader.JACOB_DLL_PATH, lib);
        LibraryLoader.loadJacobLibrary();
    }

    /**
     * 获取证书的目录，（全路径,emmmm）,并且把证书拷贝出来。
     *
     * @param dir 文件名
     * @return 返回一个字符串
     */
    public static String copyFile(String dir, String copyPath) {
        File targetFile;
        try {
            targetFile = new File(copyPath);
        } catch (Exception e) {
            log.info("呀，文件查找失败了。。。");
            return dir;
        }
        // 如果证书文件不存在，则再运行目录把文件拷贝到同目录下
        if (!targetFile.exists()) {
            log.info("文件：{},不存在，正在Copy到{}。。。", dir, copyPath);
            ClassPathResource resource = new ClassPathResource(dir);
            InputStream inputStream = null;
            try {
                inputStream = resource.getInputStream();
                FileUtils.copyInputStreamToFile(inputStream, targetFile);
            } catch (Exception e) {
                log.error("文件:{},复制到{}失败", dir, copyPath);
                log.info("请手动把 【{}】 文件复制到 【{}】,再重新启动", dir, copyPath);
                return dir;
            } finally {
                try {
                    if (inputStream != null) {
                        // 要关闭资源
                        inputStream.close();
                    }
                } catch (IOException ex) {
                    log.info("文件:{},复制到{}失败", dir, copyPath);
                    return dir;
                }
            }
            log.info("文件:{},复制到{}成功", dir, copyPath);
        }
        return dir;
    }

}
